#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include <stdio.h>


#define ERR_EXIT(m) \
    do { \
        perror(m); \
        exit(EXIT_FAILURE); \
    } while(0)      

const int gshm_id = -1;
const int gsize = 4096;
const std::string gpath = ".";
const int gproj_id = 1000;

class Shm
{
public:
    //构造函数
    Shm() : _size(gsize), _shmid(gshm_id)
    {

    }

    //申请共享内存
    void Create()
    {
        //获取key
        key_t k = ftok(gpath.c_str(), gproj_id);
        if(k == -1)
        {
            ERR_EXIT("ftok");            
        }
        printf("key: %d\n", k);//打印key

        int n = shmget(k, _size, IPC_CREAT | IPC_EXCL);
        if(n < 0)
        {
            ERR_EXIT("shmget");
        }
        printf("shmget: %d\n", n);//打印shmget
    }


    //析构函数
    ~Shm()
    {}
private:
    int _shmid;
    int _size;
};